package com.kk.xhr.admin.biz.impl;

import com.kk.xhr.admin.biz.IContractBizService;
import com.kk.xhr.admin.controller.request.ContractAddRequest;
import com.kk.xhr.admin.controller.request.ContractModifyRequest;
import com.kk.xhr.admin.controller.request.ContractQueryRequest;
import com.kk.xhr.admin.controller.vo.ContractVO;
import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.dto.ContractDTO;
import com.kk.xhr.model.dto.PageDto;
import com.kk.xhr.model.service.IContractService;
import com.kk.xhr.model.service.IUserService;
import com.kk.xhr.util.DateUtil;
import com.kk.xhr.web.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 合同biz服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/5
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class ContractBizServiceImpl implements IContractBizService {
    private final IContractService contractService;
    private final IUserService userService;

    @Override
    public PageVO<ContractVO> queryPage(ContractQueryRequest request) {
        PageDto<ContractDTO> pageDto = contractService
            .queryPage(request.getUserId(), request.getLimit(), request.getOffset());
        return PageVO.fromDTO(pageDto, dto -> ContractVO.builder()
            .id(dto.getId())
            .name(userService.queryName(dto.getUserId()))
            .term(dto.getTerm())
            .begin(dto.getBegin())
            .end(dto.getEnd())
            .conversation(dto.getConversation())
            .fileUrl(dto.getFileId())
            .status(dto.getStatus())
            .build());
    }

    @Override
    public boolean add(ContractAddRequest request) {
        return contractService.add(ContractDTO.builder()
            .userId(request.getUserId())
            .begin(DateUtil.validTime(request.getBegin()))
            .end(DateUtil.validTime(request.getEnd()))
            .term((double) (Duration.between(DateUtil.validTime(request.getBegin()), DateUtil.validTime(request.getEnd())).toDays()))
            .conversation(DateUtil.validTime(request.getConversation()))
            .fileId(request.getFileId())
            .build());
    }

    @Override
    public boolean modify(Long id, ContractModifyRequest request) {
        return contractService.modify(ContractDTO.builder()
            .id(id)
            .begin(DateUtil.validTime(request.getBegin()))
            .end(DateUtil.validTime(request.getEnd()))
            .term((double) (Duration.between(DateUtil.validTime(request.getBegin()), DateUtil.validTime(request.getEnd())).toDays()))
            .conversation(DateUtil.validTime(request.getConversation()))
            .fileId(request.getFileId())
            .build());
    }

    @Override
    public boolean modifyStatus(Long id, BinaryEnum status) {
        return contractService.modifyStatus(id, status);
    }
}
